package com.jukte.recipe.share;

import com.ewhat.recipes.R;
import com.jukte.recipe.utils.AppUtility;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class TwitterShareActivity extends Activity implements OnClickListener {
	private int TWITTER_AUTH;
	private Twitter mTwitter;
	private RequestToken mRequestToken;
	SharedPreferences settings;

	private String accessToken;
	private String accessTokenSecret;

	private boolean haveConnectedWifi;
	private boolean haveConnectedMobile;
	private double x;
	private Button loginBtn, logoutBtn, shareBtn;
	private ProgressDialog pDialog;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.twitter_share);

		SharedPreferences settings = PreferenceManager
				.getDefaultSharedPreferences(this);
		accessToken = settings.getString("twitter_access_token", null);
		accessTokenSecret = settings.getString("twitter_access_token_secret",
				null);
		shareBtn = (Button) findViewById(R.id.tweet_button);
		loginBtn = (Button) findViewById(R.id.login_btn);
		logoutBtn = (Button) findViewById(R.id.logout_btn);
		shareBtn.setOnClickListener(this);
		loginBtn.setOnClickListener(this);
		logoutBtn.setOnClickListener(this);

	}

	/*private boolean haveNetworkConnection() {
		haveConnectedWifi = false;
		haveConnectedMobile = false;

		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] netInfo = cm.getAllNetworkInfo();
		for (NetworkInfo ni : netInfo) {
			if (ni.getTypeName().equalsIgnoreCase("WIFI"))
				if (ni.isConnected())
					haveConnectedWifi = true;
			if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
				if (ni.isConnected())
					haveConnectedMobile = true;
		}
		return haveConnectedWifi || haveConnectedMobile;
	}*/

	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub

		if (requestCode == TWITTER_AUTH) {

			if (resultCode == Activity.RESULT_OK) {
				// Toast.makeText(this, "Hey Ho", 300).show();
				String oauthVerifier = (String) data.getExtras().get(
						"oauth_verifier");

				AccessToken at = null;

				try {
					// Pair up our request with the response
					at = mTwitter.getOAuthAccessToken(oauthVerifier);
					String theToken = at.getToken();
					// Toast.makeText(this, theToken, 10000).show();
					String theTokenSecret = at.getTokenSecret();
					// Toast.makeText(this, theTokenSecret, 10000).show();
					// SharedPreferences settings =
					// PreferenceManager.getDefaultSharedPreferences(this);
					settings = PreferenceManager
							.getDefaultSharedPreferences(this);
					SharedPreferences.Editor editor = settings.edit();
					editor.putString("twitter_access_token", theToken);
					editor.putString("twitter_access_token_secret",
							theTokenSecret);
					editor.commit();

					
				} catch (TwitterException e) {
					e.printStackTrace();
				}
			}
		} else {
			Toast.makeText(this, "uh oh, Spaghetti Os", 300).show();
		}

	}

	class updateTwitterStatus extends AsyncTask<String, String, String> {

		/**
		 * 
		 * Before starting background thread Show Progress Dialog
		 * 
		 * */

		@Override
		protected void onPreExecute() {

			super.onPreExecute();
			pDialog = new ProgressDialog(TwitterShareActivity.this);
			pDialog.setMessage("Updating to twitter...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();

		}

		protected String doInBackground(String... args) {

			Log.d("Tweet Text", "> " + args[0]);
			String status = args[0];
			ConfigurationBuilder builder = new ConfigurationBuilder();
			builder.setOAuthConsumerKey(Constants.CONSUMER_KEY);
			builder.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
			builder.setOAuthAccessToken(accessToken);
			builder.setOAuthAccessTokenSecret(accessTokenSecret);
			Configuration conf = builder.build();
			Twitter t = new TwitterFactory(conf).getInstance();

			try {
				x = Math.random();
				t.updateStatus(status+"\n"+x);

			} catch (TwitterException e) {
				e.printStackTrace();
			}

			return null;

		}

		protected void onPostExecute(String file_url) {

			// dismiss the dialog after getting all products

			pDialog.dismiss();
			runOnUiThread(new Runnable() {

				@Override
				public void run() {

					Toast.makeText(getApplicationContext(),
							"Status tweeted successfully", Toast.LENGTH_SHORT)
							.show();

				}

			});

		}

	}

	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		settings = PreferenceManager.getDefaultSharedPreferences(this);

		accessToken = settings.getString(Constants.PREF_KEY_OAUTH_TOKEN, null);
		accessTokenSecret = settings.getString(Constants.PREF_KEY_OAUTH_SECRET,
				null);
		if ((accessToken == null) || (accessTokenSecret == null)) {
			logoutBtn.setVisibility(View.GONE);
			shareBtn.setVisibility(View.GONE);
			loginBtn.setVisibility(View.VISIBLE);
		} else {
			logoutBtn.setVisibility(View.VISIBLE);
			shareBtn.setVisibility(View.VISIBLE);
			loginBtn.setVisibility(View.GONE);
		}

	}

	Runnable loginThread= new Runnable() {
		public void run() {
			doLogIn();
		}
	}; 
	
	
	
	private void doLogIn() {
		mTwitter = new TwitterFactory().getInstance();
		mRequestToken = null;
		mTwitter.setOAuthConsumer(Constants.CONSUMER_KEY,
				Constants.CONSUMER_SECRET);
		String callbackURL = getResources()
				.getString(R.string.twitter_callback);
		try {
			mRequestToken = mTwitter.getOAuthRequestToken(callbackURL);
			Intent i = new Intent(this, TwitterWebviewActivity.class);
			i.putExtra("URL", mRequestToken.getAuthenticationURL());
			startActivityForResult(i, TWITTER_AUTH);
		} catch (TwitterException e) {
			e.printStackTrace();
			Toast.makeText(this, "Could Not connect! Please try again later!!",
					3000).show();
		}
		
	}

	private void doLogOut() {

		// Clear the shared preferences

		Editor e = settings.edit();
		e.remove(Constants.PREF_KEY_OAUTH_TOKEN);
		e.remove(Constants.PREF_KEY_OAUTH_SECRET);
		e.commit();

		logoutBtn.setVisibility(View.GONE);
		shareBtn.setVisibility(View.GONE);
		loginBtn.setVisibility(View.VISIBLE);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == shareBtn) {
			
			if (AppUtility.isInternetConnected(TwitterShareActivity.this)) {
				
				String status="I Love Quinoa-So I got the FREE APP with over 160 Quinoa Recipes.Get Yours Too..https://play.google.com/store/apps/details?id=com.ewhat.recipes";
				new updateTwitterStatus().execute(status);
				// updateStatus();
			} else {
				Toast.makeText(this, "No access to Internet..please try again",
						3000).show();
			}
		} else if (v == loginBtn) {
			if (AppUtility.isInternetConnected(TwitterShareActivity.this)) {
				//doLogIn();
				Thread thread = new Thread(null, loginThread, "MagentoBackground");
				thread.start();
			}
			else {
				Toast.makeText(this, "No access to Internet..please try again",
						3000).show();}
		} else if (v == logoutBtn) {
			doLogOut();
		}
	}
}
